package xyz.yuanjilu.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baidu.aip.ocr.AipOcr;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import xyz.yuanjilu.service.OcrService;
import xyz.yuanjilu.utils.RRException;
import xyz.yuanjilu.utils.StringUtils;

@Service
public class OcrServiceImpl implements OcrService{
	private Logger logger = LoggerFactory.getLogger(getClass());
	//设置APPID/AK/SK
    public static final String APP_ID = "10070343";
    public static final String API_KEY = "HoMjBuMSglILs8dKyDQp4GI5";
    public static final String SECRET_KEY = "n0FodWyeWybhUme5cS1QpEBtMwf6OCqt";
    // 初始化一个OcrClient
    public static final  AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    @Value("${java.io.tmpdir}")
	private String temdir;
    @Resource(name="ocrCache")
	private Cache cache;
	@Override
	public JSONObject plateLicense(File imgFile) {
		JSONObject response ;
		try {
			response = client.plateLicense(readImageFile(imgFile));
			if (response.has("error_code")) {//默认车牌识别出现错误，调用通用ocr识别
				HashMap<String, String> options= new HashMap<>();
				response = client.basicGeneral(readImageFile(imgFile), options);
				if (response.has("error_code")) {//默认如果通用检测出现错误，抛出异常
					throw new RRException("解析车牌图片异常");
				}
				JSONArray jsonArray = response.getJSONArray("words_result");
				String carPlateNumber= "" ;
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					carPlateNumber += jsonObject.getString("words");
				}
				carPlateNumber=StringUtils.exceptSymbol(carPlateNumber);
				JSONObject response2 = new JSONObject();
				response2.put("number", carPlateNumber);
				response=new JSONObject();
				response.put("words_result", response2);
			}
			String string = response.toString();
			System.out.println(string);
		} catch (Exception e) {
			throw new RRException("解析车牌图片异常", e);
		}

		return response;
	}

	@Override
	public JSONObject plateLicense(String imgFilePath) {

		return this.plateLicense(new File(imgFilePath));
	}

	public byte[] readImageFile(File file) throws Exception {
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		in = new FileInputStream(file);
		data = this.readImage(in);
		return data;
	}

	@Override
	public JSONObject plateLicenseURL(String url) {
		JSONObject plateLicense = null;
		Element element = cache.get(url);
		try {
			if (element == null) {
				URL imgFileURL = new URL(url);
				File tempfile = new File(temdir, UUID.randomUUID() + ".jpg");
				FileUtils.copyURLToFile(imgFileURL, tempfile);
				plateLicense = this.plateLicense(tempfile);
				if (plateLicense != null) {
					logger.info(url + "加入到缓存： " + cache.getName());
//					element = new Element(url, formatResult(plateLicense));
					element = new Element(url,plateLicense.toString());
					cache.put(element);
				}
			} else {
				/*com.alibaba.fastjson.JSONObject temp = (com.alibaba.fastjson.JSONObject) element.getObjectValue();
				plateLicense = formatResult(temp);*/
				plateLicense = new JSONObject(element.getObjectValue()+"");
				logger.info(url + "使用缓存： " + cache.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("解析车牌图片异常", e);
		}
		return plateLicense;
	}
	
	/*public com.alibaba.fastjson.JSONObject  formatResult(JSONObject JSONObject){
		com.alibaba.fastjson.JSONObject JSONObjecttem=(com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(JSONObject.toString());
		
		return JSONObjecttem;
	}
	public JSONObject  formatResult(com.alibaba.fastjson.JSONObject JSONObject ){
		JSONObject JSONObjecttem=new JSONObject(JSONObject.toJSONString());
		
		return JSONObjecttem;
	}*/
	public byte[] readImage(InputStream in) throws Exception {
		byte[] data = null;
		// 读取图片字节数组
		data = new byte[in.available()];
		in.read(data);
		in.close();
		// 对字节数组Base64编码
		return data;// 返回Base64编码过的字节数组字符串
	}
}
